﻿using UnityEngine.Networking;

namespace LitFramework
{
    public class GameState_ForceUpdate : IState
    {
        public StateMechine Master { get; set; }

        private UnityWebRequest versionRequest;

        public void OnEnter(params object[] values)
        {
            GameManager.Instance.InitState = "ForceUpdate Check...";
            GameManager.Instance.InitProgress = 0;

            var url = ProjectConfig.Config.cdn + $"/Bundles/{ProjectConfig.Env}/app.version";
            versionRequest = UnityWebRequest.Get(url);
            versionRequest.timeout = 30;
            versionRequest.SendWebRequest();
        }

        public void OnUpdate()
        {
            switch (versionRequest.result)
            {
                case UnityWebRequest.Result.InProgress:
                    var progress = versionRequest.downloadProgress;
                    GameManager.Instance.InitProgress = progress;
                    break;
                case UnityWebRequest.Result.Success:
                    var code = int.Parse(versionRequest.downloadHandler.text);
                    CheckAppCode(code);
                    break;
                case UnityWebRequest.Result.ConnectionError:
                case UnityWebRequest.Result.ProtocolError:
                case UnityWebRequest.Result.DataProcessingError:
                    TipPanel.ShowTip(versionRequest.error, "好的", null);
                    break;
                default:
                    break;
            }
        }

        private void CheckAppCode(int code)
        {
            if (code > ProjectConfig.Config.appCode)
            {
                //强制更新提示
                TipPanel.ShowTip("请前往应用商店更新App", "好的", null);
            }
            else
            {
                GameManager.Instance.InitState = "ForceUpdate Check Complete";
                GameManager.Instance.InitProgress = 1;
                Master.TurnToState<GameState_HotUpdate>();
            }
        }

        public void OnExit()
        {

        }
    }
}
